#include <stdlib.h>

#include "pear_redis.h"
#include "log/pear_log.h"
#include "pear_kv_redis.h"
#include "pear_kv_store.h"

static char *pr_kv_redis_get(pr_kv_store_t *, char *);
static char *pr_kv_redis_del(pr_kv_store_t *, char *);
static char *pr_kv_redis_set(pr_kv_store_t *, char *, char *);

pr_kv_redis_t *pr_new_kv_redis()
{
    pr_kv_redis_t *kvr = NULL;

    kvr = (pr_kv_redis_t *) malloc(sizeof(*kvr));
    if (kvr == NULL)
    {
        PEAR_LOG("pr_kv_redis_t malloc error\n");
        return NULL;
    }

    kvr->redis = pr_new_redis(0, NULL, 0);
    if (kvr->redis == NULL)
    {
        PEAR_LOG("new_pr_redis error\n");
        free(kvr);
        return NULL;
    }

    kvr->handler.get = &pr_kv_redis_get;
    kvr->handler.set = &pr_kv_redis_set;
    kvr->handler.del = &pr_kv_redis_del;
    kvr->handler.upd = &pr_kv_redis_set;

    return kvr;
}

static char *pr_kv_redis_get(pr_kv_store_t *kvs, char *key)
{
    char *value = NULL;

    pr_kv_redis_t *kvr = (pr_kv_redis_t *) kvs;

    if ((value = pr_redis_get(kvr->redis, key)) == NULL)
    {
        PEAR_LOG("pr_redis_get Error\n");
        return NULL;
    }

    return value;
}

static char *pr_kv_redis_set(pr_kv_store_t *kvs, char *key, char *value)
{
    pr_kv_redis_t *kvr = (pr_kv_redis_t *) kvs;

    if (pr_redis_set(kvr->redis, key, value) < 0)
    {
        PEAR_LOG("pr_redis_get Error\n");
        return NULL;
    }

    return value;
}

/*
 * set action = update action in redis;
 *
 * static char *pr_kv_redis_upt(pr_kv_store_t *kvs, char *key, char *value)
 * {
 *     pr_kv_redis_t *kvr = (pr_kv_redis_t *) kvs;
 * 
 *     return NULL;
 * }
 */

static char *pr_kv_redis_del(pr_kv_store_t *kvs, char *key)
{
    char *value = NULL;

    pr_kv_redis_t *kvr = (pr_kv_redis_t *) kvs;

    if (pr_redis_del(kvr->redis, key) < 0)
    {
        PEAR_LOG("pr_redis_get Error\n");
        return NULL;
    }

    return value;
}



